const  Router  =  require('koa-router');
const  router  =  new   Router();
const passport = require('koa-passport');
//引入个人信息模板实例
const  Profile = require('../model/Profiles');
// 引入验证
const validateProfileInput = require('../validation/profile');
const validateExperienceInput = require('../validation/experience');
const validateEducationInput = require('../validation/education');
/*
  get  请求
  注册接口
  http://localhost:5000/api/user/test
*/
router.get('/test',async  ctx=>{
    ctx.status=200;
    ctx.body={ msg:'hello  world  '};  //{"msg":"hello  world"}
})
/**
 * @route GET api/profiles/
 * @desc  个人信息接口地址 
 * @access 接口是私密的
 */
router.get('/', passport.authenticate('jwt', { session: false }), async ctx => {
  // console.log(ctx.state.user);
  const profile = await Profile.find({ user: ctx.state.user.id }).populate(
    'user',
    ['name', 'avatar']
  );
  if (profile.length > 0) {
    ctx.status = 200;
    ctx.body = profile[0];
  } else {
    ctx.status = 404;
    ctx.body = { noprofile: '该用户没有任何相关的个人信息' };
    return;
  }
});
/**
 * @route post api/profile/
 * @desc  添加和编辑个人信息接口地址 
 * @access 接口是私密的
 */
router.post('/', passport.authenticate('jwt', { session: false }), async ctx => {
  //验证
    const { errors, isValid } = validateProfileInput(ctx.request.body);
    // 判断是否验证通过
    if (!isValid) {
      ctx.status = 400;
      ctx.body = errors;
      return;
    }
  //1.传入的数据
      const  profileFields = {};
      //user
      profileFields.user=ctx.state.user.id;
      //handle
      if(ctx.request.body.handle) {
        profileFields.handle = ctx.request.body.handle;
      }
      //company
      if(ctx.request.body.company) {
        profileFields.company = ctx.request.body.company;
      }
      //website
      if(ctx.request.body.website) {
        profileFields.website = ctx.request.body.website;
      }
      //location
      if(ctx.request.body.location) {
        profileFields.location = ctx.request.body.location;
      }
      //status
      if(ctx.request.body.status) {
        profileFields.status = ctx.request.body.status;
      }
      //bio
      if(ctx.request.body.bio) {
        profileFields.bio = ctx.request.body.bio;
      }
      //githubusername
      if(ctx.request.body.githubusername) {
        profileFields.githubusername = ctx.request.body.githubusername;
      }
      //skills
      if(typeof ctx.request.body.skills!=='undefined') {
        profileFields.skills = ctx.request.body.skills.split(',');
      }
      //
      profileFields.social= {};
      if(ctx.request.body.wechat){
        profileFields.social.wechat = ctx.request.body.wechat;
      }
      if(ctx.request.body.QQ){
        profileFields.social.QQ = ctx.request.body.QQ;
      }
      if(ctx.request.body.tengxunkt){
        profileFields.social.tengxunkt = ctx.request.body.tengxunkt;
      }
      if(ctx.request.body.wangyikt){
        profileFields.social.wangyikt = ctx.request.body.wangyikt;
      }
  //2.数据库查询数据,根据用户id 查找，并且储存起来
      const profile  = await Profile.find({ user: ctx.state.user.id });
      //3.判断，如果数据大于0 ,就进行编辑
      if(profile.length>0) {
          //编辑更新
          const  profileUpdate =  await   Profile.findOneAndUpdate(
            {
             users:ctx.state.user.id
            },
            {
              $set:profileFields
            },
            {
               new:true
            }
        );
        ctx.body=profileUpdate;
      }
      //4.判断，如果数据小于0 ,就进行添加
      else {
         //添加
         await new Profile(profileFields).save().then(profile=>{
               ctx.status=200;
               ctx.body=profile;
         })
      }
});

/**
 * @route post api/profile/handle?handle=123
 * @desc  通过handle获取个人信息接口地址 
 * @access 接口是公开的
 */
router.get('/handle',async  ctx=>{
  const errors = {};
  const handle = ctx.query.handle;
  // console.log(handle);
  const profile = await Profile.find({ handle: handle }).populate('user', [
    'name',
    'avatar'
  ]);
  // console.log(profile);

  if (profile.length < 1) {
    errors.noprofile = '未找到该用户信息';
    ctx.status = 404;
    ctx.body = errors;
  } else {
    ctx.body = profile[0];
  }
})

/**
 * @route GET api/profile/user?user_id=blabla
 * @desc  通过user_id获取个人信息接口地址
 * @access 接口是公开的
 */
router.get('/user', async ctx => {
  const errors = {};
  const user_id = ctx.query.user_id;
  const profile = await Profile.find({ user: user_id }).populate('user', [
    'name',
    'avatar'
  ]);
  // console.log(profile);

  if (profile.length < 1) {
    errors.noprofile = '未找到该用户信息';
    ctx.status = 404;
    ctx.body = errors;
  } else {
    ctx.body = profile[0];
  }
});

/**
 * @route GET api/profile/all
 * @desc  获取所有人信息接口地址
 * @access 接口是公开的
 */
router.get('/all', async ctx => {
  const errors = {};
  const profiles = await Profile.find({}).populate('user', ['name', 'avatar']);

  if (profiles.length < 1) {
    errors.noprofile = '没有任何用户信息';
    ctx.status = 404;
    ctx.body = errors;
  } else {
    ctx.body = profiles;
  }
});



/**
 * @route post api/profile/experience
 * @desc  工作经历接口
 * @access 接口是私密的
 */
// localhost:4000/api/profile/experience
router.post(
  '/experience',
  passport.authenticate('jwt', { session: false }),
  async ctx => {
    const { errors, isValid } = validateExperienceInput(ctx.request.body);

    // 判断是否验证通过
    if (!isValid) {
      ctx.status = 400;
      ctx.body = errors;
      return;
    }
    const profileFields = {};
    profileFields.experience = [];

    const profile = await Profile.find({ user: ctx.state.user.id });

    if (profile.length > 0) {
      const newExp = {
        title: ctx.request.body.title,
        current: ctx.request.body.current,
        company: ctx.request.body.company,
        location: ctx.request.body.location,
        from: ctx.request.body.from,
        to: ctx.request.body.to,
        description: ctx.request.body.description
      };

      profileFields.experience.unshift(newExp);

      const profileUpdate = await Profile.update(
        { user: ctx.state.user.id },
        { $push: { experience: profileFields.experience } },
        { $sort: 1 }
      );

      // ctx.body = profileUpdate;
      if (profileUpdate.ok == 1) {
        const profile = await Profile.find({
          user: ctx.state.user.id
        }).populate('user', ['name', 'avatar']);

        if (profile) {
          ctx.status = 200;
          ctx.body = profile;
        }
      }
    } else {
      errors.noprofile = '没有该用户的信息';
      ctx.status = 404;
      ctx.body = errors;
    }
  }
);

/**
 * @route post api/profile/education
 * @desc  工作经历接口
 * @access 接口是私密的
 */
// localhost:4000/api/profile/education
router.post('/education', passport.authenticate('jwt', { session: false }), async ctx => {
  //验证
  const { errors, isValid } = validateEducationInput(ctx.request.body);
  //判断是否验证通过
  if (!isValid) {
    ctx.status = 400;
    ctx.body = errors;
    return;
  }
    const  profileFields = {};
    profileFields.education=[];
    //查找用户id是否存在
    const profile = await Profile.find({ user: ctx.state.user.id });
    //判断profile  的数据是否存在，存在就添加个人经历的数据
    if(profile.length>0) {
      //设计education 的结构数据
       const  newEdu={
        school: ctx.request.body.school,
        current: ctx.request.body.current,
        degree: ctx.request.body.degree,
        fieldofstudy: ctx.request.body.fieldofstudy,
        from: ctx.request.body.from,
        to: ctx.request.body.to,
        description: ctx.request.body.description
       }
       profileFields.education.unshift(newEdu);
       //console.log(profileFields);
       //在从前端添加数据后，我们更新数据到数据库
       const  profileUpdate =  await   Profile.update(
        {
         user:ctx.state.user.id
        },
        {
          $push: { education: profileFields.education } 
        },
        {
           $sort:1
        }
    );
        // ctx.body=profileUpdate;
        //插入成功,就再查找一次数据
        if (profileUpdate.ok == 1) {
            const profile = await Profile.find({
            user: ctx.state.user.id
          }).populate('user', ['name', 'avatar']);  //populate 表示跨表查询
          if (profile) {
            ctx.status = 200;
            ctx.body = profile;
          }
        }
  
    }else {
      errors.noprofile = '没有该用户的信息';
      ctx.status = 404;
      ctx.body = errors;
    }
    

});

//删除接口
/**
 * @route DELETE api/profile/experience?exp_id=dfasdfa
 * @desc  删除工作经验接口地址
 * @access 接口是私有的
 */
router.delete(
  '/experience',
  passport.authenticate('jwt', { session: false }),
  async ctx => {
    // 拿到id
    const exp_id = ctx.query.exp_id;
    // console.log(exp_id);

    // 查询
    const profile = await Profile.find({ user: ctx.state.user.id });
    if (profile[0].experience.length > 0) {
      // 找元素下标
      const removeIndex = profile[0].experience
        .map(item => item.id)
        .indexOf(exp_id);
      // 删除
      profile[0].experience.splice(removeIndex, 1);
      // 更新数据库
      const profileUpdate = await Profile.findOneAndUpdate(
        { user: ctx.state.user.id },
        { $set: profile[0] },
        { new: true }
      );

      ctx.body = profileUpdate;
    } else {
      ctx.status = 404;
      ctx.body = { errors: '没有任何数据' };
    }
  }
);

/**
 * @route DELETE api/profile/education?edu_id=dfasdfa
 * @desc  删除工作经验接口地址
 * @access 接口是私有的
 */

router.delete(
  '/education',
  passport.authenticate('jwt', { session: false }),
  async ctx => {
    // 拿到id
    const edu_id = ctx.query.edu_id;
    // console.log(exp_id);

    // 查询
    const profile = await Profile.find({ user: ctx.state.user.id });
    if (profile[0].education.length > 0) {
      // 找元素下标
      const removeIndex = profile[0].education
        .map(item => item.id)
        .indexOf(edu_id);
      // 删除
      profile[0].education.splice(removeIndex, 1);
      // 更新数据库
      const profileUpdate = await Profile.findOneAndUpdate(
        { user: ctx.state.user.id },
        { $set: profile[0] },
        { new: true }
      );

      ctx.body = profileUpdate;
    } else {
      ctx.status = 404;
      ctx.body = { errors: '没有任何数据' };
    }
  }
);

/**
 * @route DELETE api/profile
 * @desc  删除整个用户接口地址
 * @access 接口是私有的
 */

router.delete(
  '/',
  passport.authenticate('jwt', { session: false }),
  async ctx => {
    const profile = await Profile.deleteOne({ user: ctx.state.user.id });
    if (profile.ok == 1) {
      const user = await User.deleteOne({ _id: ctx.state.user.id });
      if (user.ok == 1) {
        ctx.status = 200;
        ctx.body = { success: true };
      }
    } else {
      ctx.status = 404;
      ctx.body = { error: 'profile不存在' };
    }
  }
);

module.exports = router.routes();
